import Taro from "@tarojs/taro";

export interface RequestOption {
  path: string;
  data?: any;
}

const testUrl = "https://testapi.qpscrm.com";

class MyRequest {
  private baseUrl: string; // baseUrl
  constructor(props) {
    this.baseUrl = props;
  }

  // get请求
  getRequest = async (params: RequestOption) => {
    return Taro.request({
      method: "GET",
      url: `${this.baseUrl}${params.path}`,
      data: params.data,
    });
  };

  // post请求
  postRequest = async (params: RequestOption) => {
    return Taro.request({
      method: "POST",
      url: `${this.baseUrl}${params.path}`,
      data: params.data,
    });
  };
}

Taro.addInterceptor((chain) => {
  const { requestParams } = chain;
  requestParams.header = {
    ...requestParams.header,
    Authorization: `Bearer ${Taro.getStorageSync("token")}`,
  };
  return (
    chain
      .proceed(requestParams)
      // 对返回的是数据进行处理
      .then((res) => (res.statusCode === 200 ? res.data : {}))
  );
});

export default new MyRequest(testUrl);
